package searchkeyword

import (
	"context"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetSearchKeywordByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetSearchKeywordByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetSearchKeywordByIdLogic {
	return &BackendGetSearchKeywordByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetSearchKeywordByIdLogic) BackendGetSearchKeywordById(in *backend.IDReq) (*backend.SearchKeywordInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.SearchKeyword.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var sort *uint32
	if res.Sort != uint16(globalkey.SystemDefaultSort) {
		sort = pointy.GetPointer(uint32(res.Sort))
	}
	now := time.Now()
	var pending *uint32
	if res.StartedAt.Valid && res.StartedAt.Time.After(now) {
		pending = pointy.GetPointer(uint32(1))
	}
	var expired *uint32
	if res.EndedAt.Valid && res.EndedAt.Time.Before(now) {
		expired = pointy.GetPointer(uint32(1))
	}

	return &backend.SearchKeywordInfo{
		Id:         &res.ID,
		Type:       pointy.GetPointer(uint32(res.Type)),
		Title:      &res.Title,
		LinkType:   pointy.GetPointer(uint32(res.LinkType)),
		LinkUrl:    &res.LinkURL,
		ObjectType: pointy.GetPointer(uint32(res.ObjectType)),
		ObjectId:   &res.ObjectID,
		Status:     pointy.GetPointer(uint32(res.Status)),
		Sort:       sort,
		CreatedAt:  pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:  pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:  pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		StartedAt:  pointy.GetPointer(modelx.FormatNullDotTime(res.StartedAt, "")),
		EndedAt:    pointy.GetPointer(modelx.FormatNullDotTime(res.EndedAt, "")),
		Pending:    pending,
		Expired:    expired,
	}, nil
}
